package com.wuxin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.wuxin.dto.ExcelDictDTO;
import com.wuxin.entity.Dict;
import com.wuxin.listener.ExcelDictDTOListener;
import com.wuxin.mapper.DictMapper;
import com.wuxin.service.DictService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author wuxin
 * @since 2025-01-13
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream,
                ExcelDictDTO.class,new ExcelDictDTOListener(baseMapper)).sheet().doRead();
        System.out.println("service import ok !");
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        List<Dict> dictList = baseMapper.
                selectList(new QueryWrapper<Dict>().eq("parent_id",parentId));
        dictList.forEach(dict -> {
            //如果是子节点，则是非叶子节点
            boolean result = this.hasChildren(dict.getId());
            //设置
            dict.setHasChildren(result);
        });


        return dictList;
    }

    @Override
    public List listData() {
        List<Dict> dictList =  baseMapper.selectList(null);

        List<ExcelDictDTO>  excelDictDTOList = new ArrayList<>(dictList.size());

        dictList.forEach(dict -> {
            ExcelDictDTO eddo = new ExcelDictDTO();
            //使用拷贝方法
            BeanUtils.copyProperties(dict,eddo);
            //  eddo.setDictCode(dict.getName()); 依次赋值
            excelDictDTOList.add(eddo);
        });

        return excelDictDTOList;
    }

    //判断当前节点是否存在子节点
    private boolean hasChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);

        Integer count = baseMapper.selectCount(wrapper);

        if(count.intValue()>0){
            //存在子节点
            return true;
        }
        return false;
    }
}
